using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MessagesController : ControllerBase
    {
        private readonly IMessageService _messageService;

        public MessagesController(IMessageService messageService)
        {
            _messageService = messageService;
        }

        /// <summary>
        /// 获取所有消息
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Message>>> GetAllMessages()
        {
            var messages = await _messageService.GetAllAsync();
            return Ok(messages);
        }

        /// <summary>
        /// 根据ID获取消息
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Message>> GetMessage(Guid id)
        {
            var message = await _messageService.GetByIdAsync(id);
            if (message == null)
            {
                return NotFound($"消息 {id} 不存在");
            }
            return Ok(message);
        }

        /// <summary>
        /// 根据对话ID获取消息列表
        /// </summary>
        [HttpGet("conversation/{conversationId}")]
        public async Task<ActionResult<IEnumerable<Message>>> GetMessagesByConversation(Guid conversationId)
        {
            var messages = await _messageService.GetByConversationIdAsync(conversationId);
            return Ok(messages);
        }

        /// <summary>
        /// 根据发送者获取消息列表
        /// </summary>
        [HttpGet("sender/{sender}")]
        public async Task<ActionResult<IEnumerable<Message>>> GetMessagesBySender(string sender)
        {
            var messages = await _messageService.GetBySenderAsync(sender);
            return Ok(messages);
        }

        /// <summary>
        /// 获取引用特定文档的消息列表
        /// </summary>
        [HttpGet("document/{documentId}")]
        public async Task<ActionResult<IEnumerable<Message>>> GetMessagesWithDocumentReference(Guid documentId)
        {
            var messages = await _messageService.GetMessagesWithDocumentReferenceAsync(documentId);
            return Ok(messages);
        }

        /// <summary>
        /// 获取对话中的最新消息
        /// </summary>
        [HttpGet("conversation/{conversationId}/latest")]
        public async Task<ActionResult<Message>> GetLatestMessage(Guid conversationId)
        {
            var message = await _messageService.GetLatestMessageAsync(conversationId);
            if (message == null)
            {
                return NotFound($"对话 {conversationId} 中没有消息");
            }
            return Ok(message);
        }

        /// <summary>
        /// 获取对话中的最近消息列表
        /// </summary>
        [HttpGet("conversation/{conversationId}/recent")]
        public async Task<ActionResult<IEnumerable<Message>>> GetRecentMessages(
            Guid conversationId, 
            [FromQuery] int count = 50)
        {
            var messages = await _messageService.GetRecentMessagesAsync(conversationId, count);
            return Ok(messages);
        }

        /// <summary>
        /// 创建新消息
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Message>> CreateMessage([FromBody] CreateMessageRequest request)
        {
            try
            {
                var message = await _messageService.CreateAsync(
                    request.ConversationId, 
                    request.Sender, 
                    request.Content, 
                    request.Reply, 
                    request.ReferencedDocId);
                return CreatedAtAction(nameof(GetMessage), new { id = message.Id }, message);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建消息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新消息
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateMessage(Guid id, [FromBody] Message message)
        {
            if (id != message.Id)
            {
                return BadRequest("消息ID不匹配");
            }

            try
            {
                await _messageService.UpdateAsync(message);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新消息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteMessage(Guid id)
        {
            try
            {
                await _messageService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除消息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新消息回复
        /// </summary>
        [HttpPut("{id}/reply")]
        public async Task<IActionResult> UpdateReply(Guid id, [FromBody] UpdateReplyRequest request)
        {
            try
            {
                await _messageService.UpdateReplyAsync(id, request.Reply);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新回复失败: {ex.Message}");
            }
        }
    }

    // 请求模型
    public class CreateMessageRequest
    {
        public Guid ConversationId { get; set; }
        public string Sender { get; set; } = string.Empty;
        public string Content { get; set; } = string.Empty;
        public string Reply { get; set; } = string.Empty;
        public Guid? ReferencedDocId { get; set; }
    }

    public class UpdateReplyRequest
    {
        public string Reply { get; set; } = string.Empty;
    }
}
